package com.tcwlkj.uuService;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.v4.util.ArraySet;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.makeramen.roundedimageview.RoundedImageView;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.adapter.VP_Adapter;
import com.tcwlkj.uuService.enums.CheckStatus;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.DriverDetailModel;
import com.tcwlkj.uuService.model.MainMessage;
import com.tcwlkj.uuService.model.PopupModel;
import com.tcwlkj.uuService.model.UpdateMessage;
import com.tcwlkj.uuService.model.cityIDModel;
import com.tcwlkj.uuService.service.LocationService;
import com.tcwlkj.uuService.ui.CustomerServiceActivity;
import com.tcwlkj.uuService.ui.FinishOrderActivity;
import com.tcwlkj.uuService.ui.HonorsActivity;
import com.tcwlkj.uuService.ui.MessageNotificationActivity;
import com.tcwlkj.uuService.ui.MyAccount;
import com.tcwlkj.uuService.ui.PopupActivity;
import com.tcwlkj.uuService.ui.PushOrderActivity;
import com.tcwlkj.uuService.ui.RecommentActivity;
import com.tcwlkj.uuService.ui.SameCityClassroomActivity;
import com.tcwlkj.uuService.ui.SettingActivity;
import com.tcwlkj.uuService.ui.login.IDcertification;
import com.tcwlkj.uuService.ui.login.LoginActivity;
import com.tcwlkj.uuService.utils.ChcheUtils;
import com.tcwlkj.uuService.utils.CommomDialog;
import com.tcwlkj.uuService.utils.Const;
import com.tcwlkj.uuService.utils.EventCenter;
import com.tcwlkj.uuService.utils.MyDialog;
import com.tcwlkj.uuService.utils.MyListView;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.ToastUtil;
import com.tcwlkj.uuService.widget.ScaleTransitionPagerTitleView;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgeAnchor;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgePagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgeRule;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import retrofit2.Call;

public class MainActivity extends AppCompatActivity {
    private String[] cehua_tit = {"荣誉榜", "邀请有奖", "同城课堂", "消息通知", "在线客服", "系统设置"};//侧滑菜单标题
    private String[] cehua_con = {"", "", "", "", "", ""};
    private int[] cehua_img = {R.mipmap.gr_03, R.mipmap.gr_05, R.mipmap.gr_04, R.mipmap.gr_xiaoxi,
            R.mipmap.gr_06, R.mipmap.gr_07};//侧滑菜单图片对应资源
    //  指示标题集合
    private List<String> list_title = new ArrayList<>();
    //  抽屉布局
    @Bind(R.id.id_drawer_layout)
    DrawerLayout drawer;
    //  导航条
    @Bind(R.id.nav_view)
    NavigationView navView;
    //viewpager
    @Bind(R.id.vp_main)
    ViewPager vpMain;
    //  万能指示器标题
    @Bind(R.id.magic_title_main)
    MagicIndicator magicTitleMain;

    private View headerLayout;
    private Intent mServiceIntent;
    private TextView tv_today_cj;
    private TextView tv_all_cj;
    private TextView tv_now_state;
    private TextView tv_username;
    private TextView tv_worknum_percenter;
    private RoundedImageView roundedImageView;
    private CommonNavigatorAdapter commonNavigatorAdapter;

    private static String NONUMBER = "0";
    private static String WAITNUMBER = "0";
    private ImageView img_star01_percenter;
    private ImageView img_star02_percenter;
    private ImageView img_star03_percenter;
    private ImageView img_star04_percenter;
    private ImageView img_star05_percenter;

    private ActionDialog actionDialog;
    private CommomDialog commonDialog;
    private SpeechSynthesizer mTts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        Const.main = this;
        initVIew();
        getDdetail();//获取用户详情
        mServiceIntent = new Intent(MainActivity.this, LocationService.class);
        startService(mServiceIntent);
        EventBus.getDefault().register(this);
        SpeechUtility.createUtility(MainActivity.this, SpeechConstant.APPID + "=59bcd239");
        showActionPopup();
        if (getIntent().getStringExtra("NotifyID")!=null&&getIntent().getStringExtra("NotifyID").equals("1")) {
            Intent intent1 = new Intent(MainActivity.this, PushOrderActivity.class);
            intent1.putExtra("OrderDetail", getIntent().getStringExtra("OrderDetail"));
            intent1.putExtra("type", getIntent().getStringExtra("type"));
            startActivity(intent1);
        }
        if(getIntent().getStringExtra("NotifyID")!=null&&getIntent().getStringExtra("NotifyID").equals("-55")){
            EventBus.getDefault().post(new EventCenter<String>(-55,getIntent().getStringExtra("notifybody")));
        }
        if(getIntent().getStringExtra("NotifyID")!=null&&getIntent().getStringExtra("NotifyID").equals("-12")){
            EventBus.getDefault().post(new EventCenter<String>(222, "取消订单"));
            EventBus.getDefault().post(new EventCenter<String>(-12, "取消订单"));
        }
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getStringExtra("NotifyID")!=null&&intent.getStringExtra("NotifyID").equals("1")) {
            Intent intent1 = new Intent(MainActivity.this, PushOrderActivity.class);
            intent1.putExtra("OrderDetail", intent.getStringExtra("OrderDetail"));
            intent1.putExtra("type", intent.getStringExtra("type"));
            startActivity(intent1);
        }
        if(intent.getStringExtra("NotifyID")!=null&&intent.getStringExtra("NotifyID").equals("-55")){
            EventBus.getDefault().post(new EventCenter<String>(-55,intent.getStringExtra("notifybody")));
        }
        if(intent.getStringExtra("NotifyID")!=null&&intent.getStringExtra("NotifyID").equals("-12")){
            EventBus.getDefault().post(new EventCenter<String>(222, "取消订单"));
            EventBus.getDefault().post(new EventCenter<String>(-12, "取消订单"));
        }
    }
    private void getDdetail() {
        String userID = PreferencesUtils.getString(MyApp.getContext(), "userID");
        Call<CommonResponse<DriverDetailModel>> httpResultCall = RetrofitUtils.getRequest(this, false).ddetail(userID);
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<DriverDetailModel>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<DriverDetailModel> commonResponse = (CommonResponse<DriverDetailModel>) t;
                ChcheUtils.getInstance().setDriverDetailModel(commonResponse.getData());
                refreshstate();
                PreferencesUtils.putInt(MyApp.getContext(), PreferencesUtils.getString(MyApp.getContext(), "userID") + "work", Integer.parseInt(commonResponse.getData().getInfo().getWorkState()));
                EventBus.getDefault().post(new EventCenter<MainMessage>(100, new MainMessage(CheckStatus.get(commonResponse.getData().getBase().getState()).getValue())));
            }
            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    getDdetail();
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }
    //刷新状态
    private void refreshstate() {
        int state = ChcheUtils.getInstance().getDriverDetailModel().getBase().getState();
        switch (ChcheUtils.getInstance().getDriverDetailModel().getBase().getGrade()) {
            case "0":
                img_star01_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                img_star02_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                img_star03_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                img_star04_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                img_star05_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                break;
            case "1":
                img_star01_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star02_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                img_star03_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                img_star04_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                img_star05_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                break;
            case "2":
                img_star01_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star02_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star03_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                img_star04_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                img_star05_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                break;
            case "3":
                img_star01_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star02_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star03_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star04_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                img_star05_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                break;
            case "4":
                img_star01_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star02_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star03_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star04_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star05_percenter.setBackgroundResource(R.mipmap.gr_xingjipng_gray);
                break;
            case "5":
                img_star01_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star02_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star03_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star04_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                img_star05_percenter.setBackgroundResource(R.mipmap.gr_xingjipng);
                break;
        }

        switch (CheckStatus.get(state)) {
            case Apply://已申请未认证
                tv_now_state.setText(CheckStatus.Apply.getValue());
                tv_username.setText("同城跑男");
                tv_worknum_percenter.setText("工号:TC" + ChcheUtils.getInstance().getDriverDetailModel().getBase().getUserCode());
                break;
            case Signed://已签约
                tv_now_state.setText(CheckStatus.Signed.getValue());
                tv_username.setText(ChcheUtils.getInstance().getDriverDetailModel().getBase().getRealName());
                Glide.with(this).load(ChcheUtils.getInstance().getDriverDetailModel().getPhotos().get(0).getSamllPhoto()).error(R.mipmap.iv_touxiang).into(roundedImageView);
                tv_worknum_percenter.setText("工号:TC" + ChcheUtils.getInstance().getDriverDetailModel().getBase().getUserCode());
                break;
            case SubmitAuth://待审核
                tv_now_state.setText(CheckStatus.SubmitAuth.getValue());
                tv_username.setText(ChcheUtils.getInstance().getDriverDetailModel().getBase().getRealName());
                Glide.with(this).load(ChcheUtils.getInstance().getDriverDetailModel().getPhotos().get(0).getSamllPhoto()).error(R.mipmap.iv_touxiang).into(roundedImageView);
                tv_worknum_percenter.setText("工号:TC" + ChcheUtils.getInstance().getDriverDetailModel().getBase().getUserCode());
                break;
            case AuditNo://审核失败
                tv_now_state.setText(CheckStatus.AuditNo.getValue());
                tv_username.setText(ChcheUtils.getInstance().getDriverDetailModel().getBase().getRealName());
                Glide.with(this).load(ChcheUtils.getInstance().getDriverDetailModel().getPhotos().get(0).getSamllPhoto()).error(R.mipmap.iv_touxiang).into(roundedImageView);
                tv_worknum_percenter.setText("工号:TC" + ChcheUtils.getInstance().getDriverDetailModel().getBase().getUserCode());
                break;
            case Auditsign://待签约
                tv_now_state.setText(CheckStatus.Auditsign.getValue());
                tv_username.setText(ChcheUtils.getInstance().getDriverDetailModel().getBase().getRealName());
                Glide.with(this).load(ChcheUtils.getInstance().getDriverDetailModel().getPhotos().get(0).getSamllPhoto()).error(R.mipmap.iv_touxiang).into(roundedImageView);
                tv_worknum_percenter.setText("工号:TC" + ChcheUtils.getInstance().getDriverDetailModel().getBase().getUserCode());
                break;
            case Frozen://已冻结
                tv_now_state.setText(CheckStatus.Frozen.getValue());
                tv_username.setText(ChcheUtils.getInstance().getDriverDetailModel().getBase().getRealName());
                Glide.with(this).load(ChcheUtils.getInstance().getDriverDetailModel().getPhotos().get(0).getSamllPhoto()).error(R.mipmap.iv_touxiang).into(roundedImageView);
                tv_worknum_percenter.setText("工号:TC" + ChcheUtils.getInstance().getDriverDetailModel().getBase().getUserCode());
                break;
            case Cancle://已注销
                tv_now_state.setText(CheckStatus.Cancle.getValue());
                tv_username.setText(ChcheUtils.getInstance().getDriverDetailModel().getBase().getRealName());
                Glide.with(this).load(ChcheUtils.getInstance().getDriverDetailModel().getPhotos().get(0).getSamllPhoto()).error(R.mipmap.iv_touxiang).into(roundedImageView);
                tv_worknum_percenter.setText("工号:TC" + ChcheUtils.getInstance().getDriverDetailModel().getBase().getUserCode());
                break;
        }
        tv_all_cj.setText(ChcheUtils.getInstance().getDriverDetailModel().getDetail().getFinishOrderNum());
        tv_today_cj.setText(ChcheUtils.getInstance().getDriverDetailModel().getDetail().getDoBalance());
    }

    private void initVIew() {
        vpMain.setAdapter(new VP_Adapter(getSupportFragmentManager(), this));
        vpMain.setOffscreenPageLimit(3);
        vpMain.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

            @Override
            public void onPageSelected(int position) {
                if(position==0){
                    Const.JpushTag = true;
                    Const.isJpushTag=true;
                }else if(position==1){
                    Const.JpushTag = false;
                    Const.isJpushTag=false;
                }else if(position==2){
                    Const.JpushTag = false;
                    Const.isJpushTag=false;
                }
                Log.d("JpushTag",position+"");
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        initIndicator();//设置指示器
        drawer.closeDrawer(GravityCompat.START);
        headerLayout = navView.inflateHeaderView(R.layout.activity_person_center);
        //头像
        roundedImageView = (RoundedImageView) headerLayout.findViewById(R.id.img_header_percenter);
        LinearLayout lay_todaywork_percenter = (LinearLayout) headerLayout.findViewById(R.id.lay_todaywork_percenter);
        LinearLayout lay_allwork_percenter = (LinearLayout) headerLayout.findViewById(R.id.lay_allwork_percenter);
        LinearLayout lay_credit_percenter = (LinearLayout) headerLayout.findViewById(R.id.lay_credit_percenter);
        img_star01_percenter = (ImageView) headerLayout.findViewById(R.id.img_star01_percenter);
        img_star02_percenter = (ImageView) headerLayout.findViewById(R.id.img_star02_percenter);
        img_star03_percenter = (ImageView) headerLayout.findViewById(R.id.img_star03_percenter);
        img_star04_percenter = (ImageView) headerLayout.findViewById(R.id.img_star04_percenter);
        img_star05_percenter = (ImageView) headerLayout.findViewById(R.id.img_star05_percenter);

        tv_username = (TextView) headerLayout.findViewById(R.id.tv_username);//用户名
        tv_worknum_percenter = (TextView) headerLayout.findViewById(R.id.tv_worknum_percenter);//工号
        tv_today_cj = (TextView) headerLayout.findViewById(R.id.tv_today_cj);//账户余额
        tv_all_cj = (TextView) headerLayout.findViewById(R.id.tv_all_cj);//累计单数
        tv_now_state = (TextView) headerLayout.findViewById(R.id.tv_credit_percenter);//当前状态

        roundedImageView.setOnClickListener(new View.OnClickListener() {//点击头像
            @Override
            public void onClick(View v) {
                if(ChcheUtils.getInstance().getDriverDetailModel()==null){
                    return;
                }
                if (ChcheUtils.getInstance().getDriverDetailModel().getBase().getState() == 0 || ChcheUtils.getInstance().getDriverDetailModel().getBase().getState() == 3) {//没有认证审核或者审核失败
                    startActivity(new Intent(MainActivity.this, IDcertification.class));
                }
            }
        });
        lay_todaywork_percenter.setOnClickListener(new View.OnClickListener() {//点击账户余额
            @Override
            public void onClick(View v) {
                if(ChcheUtils.getInstance().getDriverDetailModel()==null){
                    startActivity(new Intent(MainActivity.this, MyAccount.class));
                    return;
                }
                if (ChcheUtils.getInstance().getDriverDetailModel().getBase().getState() == 0) {//没有认证审核或者审核失败
                    new CommomDialog(MainActivity.this, R.style.dialog, "您未进行身份认证，请前去认证", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            startActivity(new Intent(MainActivity.this, IDcertification.class));
                        }
                    }).show();
                } else if (ChcheUtils.getInstance().getDriverDetailModel().getBase().getState() == 3) {
                    new CommomDialog(MainActivity.this, R.style.dialog, "您的身份审核失败，是否重新审核？", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            startActivity(new Intent(MainActivity.this, IDcertification.class));
                        }
                    }).show();
                } else {
                    startActivity(new Intent(MainActivity.this, MyAccount.class));
                }
            }
        });
        lay_allwork_percenter.setOnClickListener(new View.OnClickListener() {//点击累计单数
            @Override
            public void onClick(View v) {
                if(ChcheUtils.getInstance().getDriverDetailModel()==null){
                    return;
                }
                if (ChcheUtils.getInstance().getDriverDetailModel().getBase().getState() == 0) {//没有认证审核或者审核失败
                    new CommomDialog(MainActivity.this, R.style.dialog, "您未进行身份认证，请前去认证", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            startActivity(new Intent(MainActivity.this, IDcertification.class));
                        }
                    }).show();
                } else if (ChcheUtils.getInstance().getDriverDetailModel().getBase().getState() == 3) {
                    new CommomDialog(MainActivity.this, R.style.dialog, "您的身份审核失败，是否重新审核？", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            startActivity(new Intent(MainActivity.this, IDcertification.class));
                        }
                    }).show();
                } else {
                    startActivity(new Intent(MainActivity.this, FinishOrderActivity.class));
                }
            }
        });
        lay_credit_percenter.setOnClickListener(new View.OnClickListener() {//点击当前状态
            @Override
            public void onClick(View v) {
                if(ChcheUtils.getInstance().getDriverDetailModel()==null){
                    return;
                }
                if (ChcheUtils.getInstance().getDriverDetailModel().getBase().getState() == 0 || ChcheUtils.getInstance().getDriverDetailModel().getBase().getState() == 3) {//没有认证审核或者审核失败
                    startActivity(new Intent(MainActivity.this, IDcertification.class));
                }
            }
        });
        setList();//设置抽屉栏list

        if (JPushInterface.isPushStopped(this)) {
            JPushInterface.resumePush(this);
        }
    }

    /**
     * 指示器
     */
    private void initIndicator() {
        list_title.add("实时订单");
        list_title.add("未抢订单");
        list_title.add("待完成");
        magicTitleMain.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigatorAdapter = new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return list_title == null ? 0 : list_title.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                final BadgePagerTitleView badgePagerTitleView = new BadgePagerTitleView(context);

                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                simplePagerTitleView.setText(list_title.get(index));
                simplePagerTitleView.setTextSize(15);
                simplePagerTitleView.setNormalColor(Color.parseColor("#000000"));
//              设置指示器标题文字选中的颜色（me）
                simplePagerTitleView.setSelectedColor(Color.parseColor("#FF41b1fb"));
//              指示器标题点击事件
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        vpMain.setCurrentItem(index);
                    }
                });
                badgePagerTitleView.setInnerPagerTitleView(simplePagerTitleView);

                if (index == 1) {
                    if (!NONUMBER.equals("0")) {
                        TextView badgeTextView = (TextView) LayoutInflater.from(context).inflate(R.layout.simple_count_badge_layout, null);
                        if (Integer.parseInt(NONUMBER) >= 100) {
                            badgeTextView.setText("99+");
                        } else {
                            badgeTextView.setText(NONUMBER);
                        }
                        badgePagerTitleView.setBadgeView(badgeTextView);
                        badgePagerTitleView.setXBadgeRule(new BadgeRule(BadgeAnchor.CONTENT_RIGHT, -UIUtil.dip2px(context, 6)));
                        badgePagerTitleView.setYBadgeRule(new BadgeRule(BadgeAnchor.CONTENT_TOP, 0));
                        badgePagerTitleView.setAutoCancelBadge(false);
                    }
                } else if (index == 2) {
                    if (!WAITNUMBER.equals("0")) {
                        TextView badgeTextView = (TextView) LayoutInflater.from(context).inflate(R.layout.simple_count_badge_layout, null);
                        if (Integer.parseInt(WAITNUMBER) >= 100) {
                            badgeTextView.setText("99+");
                        } else {
                            badgeTextView.setText(WAITNUMBER);
                        }
                        badgePagerTitleView.setBadgeView(badgeTextView);
                        badgePagerTitleView.setXBadgeRule(new BadgeRule(BadgeAnchor.CONTENT_RIGHT, -UIUtil.dip2px(context, 6)));
                        badgePagerTitleView.setYBadgeRule(new BadgeRule(BadgeAnchor.CONTENT_TOP, 0));
                        badgePagerTitleView.setAutoCancelBadge(false);
                    }
                }
                return badgePagerTitleView;
            }
            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
//              设置指示器动画
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(0.5f));
//              indicator.setYOffset(UIUtil.dip2px(context, 39));  //  设置指示器 的位置在上方
//              设置底部指示器的高度
                indicator.setLineHeight(UIUtil.dip2px(context, 2));
//              设置指示器的颜色
                indicator.setColors(Color.parseColor("#FF41b1fb"));
                return indicator;
            }
        };
        commonNavigator.setAdapter(commonNavigatorAdapter);
        magicTitleMain.setNavigator(commonNavigator);
        LinearLayout titleContainer = commonNavigator.getTitleContainer(); // must after setNavigator
////     保证 条目等宽
        titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        titleContainer.setDividerPadding(UIUtil.dip2px(this, 10));
        ViewPagerHelper.bind(magicTitleMain, vpMain);
    }

    /**
     * 侧滑栏listview
     */
    private void setList() {
        List<Map<String, Object>> listems = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < cehua_tit.length; i++) {
            Map<String, Object> listem = new HashMap<String, Object>();
            listem.put("img", cehua_img[i]);
            listem.put("name", cehua_tit[i]);
            listem.put("content", cehua_con[i]);
            listems.add(listem);
        }
        SimpleAdapter simplead = new SimpleAdapter(this, listems, R.layout.sideslip_list_item, new String[]{"img", "name", "content"},
                new int[]{R.id.item_image, R.id.item_tit, R.id.item_content});
        MyListView listView = (MyListView) headerLayout.findViewById(R.id.item_listview);
        listView.setAdapter(simplead);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0://荣誉榜
                        startActivity(new Intent(MainActivity.this, HonorsActivity.class));
                        break;
                    case 1://邀请有奖
                        startActivity(new Intent(MainActivity.this, RecommentActivity.class));
                        break;
                    case 2://同城课堂
                        startActivity(new Intent(MainActivity.this, SameCityClassroomActivity.class));
                        break;
                    case 3://消息通知
                        startActivity(new Intent(MainActivity.this, MessageNotificationActivity.class));
                        break;
                    case 4://在线客服
                        startActivity(new Intent(MainActivity.this, CustomerServiceActivity.class));
                        break;
                    case 5://系统设置
                        startActivity(new Intent(MainActivity.this, SettingActivity.class));
                        break;
                    default:
                        break;
                }
            }
        });
    }
    @OnClick({R.id.img_person_main, R.id.lay_hall_main})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_person_main: //大厅头像，点击打开侧滑菜单
                drawer.openDrawer(GravityCompat.START);
                break;
            case R.id.lay_hall_main:// 大厅活动通知  接口要重新下发
                showActionPopup();
                break;
            default:
                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventCenter eventCenter) {
        if (eventCenter != null && eventCenter.getEventCode() == 111) {//抢单成功
            MyDialog myDialog = new MyDialog(MainActivity.this, eventCenter.getData().toString());
            myDialog.show();
            myDialog.setClicklistener(new MyDialog.ClickListenerInterface() {
                @Override
                public void doConfirm(String msg) {
                    vpMain.setCurrentItem(3);
                    myDialog.dismiss();
                }
                @Override
                public void doCancel() {
                }
            });
        } else if (eventCenter.getEventCode() == 103) {//设置角标
            NONUMBER = eventCenter.getData().toString();
            commonNavigatorAdapter.notifyDataSetChanged();
        } else if (eventCenter.getEventCode() == 102) {//设置角标
            WAITNUMBER = eventCenter.getData().toString();
            commonNavigatorAdapter.notifyDataSetChanged();
        } else if (eventCenter.getEventCode() == 50) {//身份认证
            getDdetail();
        } else if (eventCenter.getEventCode() == 55) {//语音播报
            UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
            Speech(updateMessage.getOrderId());
        } else if (eventCenter.getEventCode() == -55) {//强制指派
            vpMain.setCurrentItem(2);
            Speech(eventCenter.getData().toString());
        } else if (eventCenter.getEventCode() == 1000) {//提现成功
            getDdetail();
        } else if (eventCenter.getEventCode() == 1002) {
            getDdetail();
        } else if (eventCenter.getEventCode() == 40111) {//退出登录
            PreferencesUtils.putBoolean(MyApp.getContext(), "Login", false);
            if (commonDialog == null) {
                commonDialog = new CommomDialog(MainActivity.this, R.style.dialog, "账号异地登录，请重新登录", new CommomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        logout();
                        ChcheUtils.getInstance().setChche();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        JPushInterface.stopPush(MyApp.getContext());
                        Const.main.finish();
                    }
                });
                commonDialog.setCancelable(false);
                commonDialog.setCanceledOnTouchOutside(false);
                commonDialog.show();
                commonDialog.setCancleVisibility(false);
            }
        } else if (eventCenter.getEventCode() == -10) {//完成订单返回首页
            vpMain.setCurrentItem(1);
            getDdetail();
        } else if (eventCenter.getEventCode() == -11) {//指派订单
            vpMain.setCurrentItem(3);
        } else if (eventCenter.getEventCode() == 222) {//取消订单
            getDdetail();
        } else if (eventCenter.getEventCode() == -12) {//商家取消订单
            commonDialog = new CommomDialog(MainActivity.this, R.style.dialog, "您的订单已被取消", new CommomDialog.OnCloseListener() {
                @Override
                public void onClick(Dialog dialog, boolean confirm) {
                }
            });
            commonDialog.show();
            commonDialog.setCancleVisibility(false);
            Speech("您的订单已被取消");
        }else if(eventCenter.getEventCode() == -9){
            if(mTts!=null&&mTts.isSpeaking()){
                mTts.stopSpeaking();
            }
        }
    }

    private void logout() {
        Call<CommonResponse<Object>> httpResultCall = RetrofitUtils.getRequest(MainActivity.this, false).logout("10002", PreferencesUtils.getString(MyApp.getContext(), "userID"));
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<Object>>() {
            @Override
            public void onSuccess(Object t) {

            }

            @Override
            public void onFail(int code, String message) {

            }
        });
    }
    private void Speech(String voice){
        if(mTts==null){
            mTts = SpeechSynthesizer.createSynthesizer(MainActivity.this, null);
        }
        mTts.setParameter(SpeechConstant.PARAMS, null);
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
        mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");//设置发音人
        mTts.setParameter(SpeechConstant.SPEED, "50");//设置语速
        //设置合成音调
        mTts.setParameter(SpeechConstant.PITCH, "50");
        mTts.setParameter(SpeechConstant.VOLUME, "80");//设置音量，范围0~100
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");
        int codes = mTts.startSpeaking(voice, mListener);
        if (codes != ErrorCode.SUCCESS) {
            if (codes == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
                //上面的语音配置对象为初始化时：
                Toast.makeText(MyApp.getContext(), "语音组件未安装", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MyApp.getContext(), "语音合成失败,错误码: " + codes, Toast.LENGTH_LONG).show();
            }
        }
    }

    private SynthesizerListener mListener = new SynthesizerListener() {
        //会话结束回调接口，没有错误时，error为null
        public void onCompleted(SpeechError error) {
        }

        //缓冲进度回调
        //percent为缓冲进度0~100，beginPos为缓冲音频在文本中开始位置，endPos表示缓冲音频在文本中结束位置，info为附加信息。
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
        }

        //开始播放
        public void onSpeakBegin() {
        }

        //暂停播放
        public void onSpeakPaused() {
        }

        //播放进度回调
        //percent为播放进度0~100,beginPos为播放音频在文本中开始位置，endPos表示播放音频在文本中结束位置.
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
        }

        //恢复播放回调接口
        public void onSpeakResumed() {
        }

        //会话事件回调接口
        public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
        ChcheUtils.getInstance().getHashMap_int().clear();
        ChcheUtils.getInstance().getYZMhashMap().clear();
    }

    public void getCity() {
        Call<CommonResponse<List<cityIDModel>>> httpResultCall = RetrofitUtils.getRequest(this, false).getCity("city");
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<List<cityIDModel>>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<List<cityIDModel>> commonResponse = (CommonResponse<List<cityIDModel>>) t;
                for (int i = 0; i < commonResponse.getData().size(); i++) {
                    if ("杭州市".equals(commonResponse.getData().get(i).getName())) {
                        Log.d("cityIDModel", commonResponse.getData().get(i).toString());
                    }
                }
            }
            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    getCity();
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }
    private void showActionPopup() {
        Call<CommonResponse<List<PopupModel>>> httpResultCall = RetrofitUtils.getRequest(MainActivity.this, false).popup(PreferencesUtils.getString(MyApp.getContext(), "userID"), "13", "1");
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<List<PopupModel>>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<List<PopupModel>> commonResponse = (CommonResponse<List<PopupModel>>) t;
                List<PopupModel> popup = commonResponse.getData();
                actionDialog = new ActionDialog(MainActivity.this, popup);
                actionDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
                actionDialog.show();
            }
            @Override
            public void onFail(int code, String message) {

            }
        });
    }
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //拦截返回键
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK){
            //判断触摸UP事件才会进行返回事件处理
            if (event.getAction() == KeyEvent.ACTION_UP) {
                onBackPressed();
            }
            //只要是返回事件，直接返回true，表示消费掉
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
    private long exitTime = 0;
    @Override
    public void onBackPressed() {
        if(System.currentTimeMillis() - exitTime > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            Const.isJpushTag=true;
            if(mTts!=null&&mTts.isSpeaking()){
                mTts.stopSpeaking();
            }
        }
    }
    public class ActionDialog extends Dialog implements AdapterView.OnItemClickListener {
        List<PopupModel> popup;
        List<String> imageUrl = new ArrayList<>();
        public ActionDialog(Context context, List<PopupModel> popup) {
            super(context);
            this.popup = popup;
        }
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.popup_action_list);
            for (int i = 0; i < popup.size(); i++) {
                imageUrl.add(i, popup.get(i).getImage());
            }
            Banner banner = (Banner) findViewById(R.id.banner);
            ImageView im_cancel = (ImageView) findViewById(R.id.img_cancel);
            banner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    Glide.with(MyApp.getContext()).load((String) path).into(imageView);
                }
            });
            banner.setImages(imageUrl);
            banner.setDelayTime(3000);
            banner.start();
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    Intent intent = new Intent(MainActivity.this, PopupActivity.class);
                    intent.putExtra("name", popup.get(position).getName());
                    intent.putExtra("url", popup.get(position).getLinkUrl());
                    startActivity(intent);
                }
            });
            im_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    actionDialog.dismiss();
                }
            });
        }
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        }
    }
}
